<?php


namespace App\Services\PHP;


use App\Services\Base;
use Illuminate\Support\Facades\Log;

class PhpApiService extends Base
{

    public function sign($data,$token)
    {
        $nonceStr = $this->random();
        $timestamp = now()->timestamp;
        $sign = $this->dealSign($nonceStr,$timestamp,$token,$data);

        return [
            //'app_id'    => env("PAWHUB_APP_ID"),
            'nonce' => $nonceStr,
            'timestamp' => $timestamp,
            'sign'    => $sign,
        ];
    }

    private function dealSign($nonceStr,$timestamp,$token,$data)
    {

        $params = [
            'nonce'     => $nonceStr,
            'token' => $token,
            'timestamp'    => $timestamp,
            'appid'          => env("PAWHUB_APP_ID"),
            'secret'          => env("PAWHUB_APP_SECRET"),
            //'data' =>$data
        ];
        ;
        if($data){
            $params['data'] = json_encode($data,JSON_UNESCAPED_UNICODE);
        }

        ksort($params);

        $keyValues = [];
        foreach ($params as $key => $value) {
            $keyValues[] = "{$key}=$value";
        }

        $str = implode('&', $keyValues);
        $str = sha1($str);
        return $str;

    }




    public function checkSignature($nonce,$timestamp,$signature,$token,$data)
    {
        $sign = $this->dealSign($nonce,$timestamp,$token,$data);
        Log::info('checkSignature--sign:'.$sign);
        if( $sign == $signature ){
            return true;
        }else{
            return false;
        }
    }




//业务参数加密
//加密规则
//str :  包含业务参数的json字串，示例: {"id":1,"age":18,"name":"shine"}
//salt:  约定盐值，示例 ：xUSOn77cialKZ34rwtxdQBDMoyySWyPbXGs7Tg8rOBM=



}